package com.itheima.web.utils;

import com.itheima.doamin.system.SysLog;
import com.itheima.doamin.system.User;
import com.itheima.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysLogService sysLogService;

    //环绕通知记录日志
    @Around("execution(* com.itheima.web.controller.system.*.*(..))")
    public Object arroudAdvice(ProceedingJoinPoint pjp){
        //判断是否登录
        User user=(User)request.getSession().getAttribute("user");
        if ( user!= null){
            //获得方法签名
            Signature signature = pjp.getSignature();
            //判断是否为方法签名
            if (signature instanceof MethodSignature){
                MethodSignature methodSignature=(MethodSignature)signature;
                Method method = methodSignature.getMethod();
                //判断是否有此注解
                boolean hasAnnotation = method.isAnnotationPresent(RequestMapping.class);
                if (hasAnnotation){
                    RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                    //通过注解获得注解的备注名
                    SysLog sysLog=new SysLog();
                    sysLog.setAction( requestMapping.name());
                    sysLog.setIp(request.getRemoteAddr());
                    sysLog.setCompanyId(user.getCompanyId());
                    sysLog.setCompanyName(user.getCompanyName());
                    sysLog.setMethod(method.getName());
                    sysLog.setTime(new Date());
                    sysLog.setUserName(user.getUserName());
                    sysLogService.save(sysLog);
                }
            }
            System.out.println(signature);
        }

        Object rtValue="error";
        Object[] args = pjp.getArgs();
        try {
            return pjp.proceed(args);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return rtValue;
    }
}
